﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DataBaseHelpers;
using DAL.Hibernate.Entities;
using UI.Web.MVC.Code.Common;
using UI.Web.MVC.Models.Home;

namespace UI.Web.MVC.Code.Helpers.Home
{
    public class HomeHelpers
    {
        #region Fields

        private readonly string _productName;

        #endregion

        public HomeHelpers(string product)
        {
            _productName = product;
        }

        public List<CreateHomeModel>  IndexGet()
        {
            string connectionString;
            using (var r = DBHelper.GetSystemRepository())
            {
                connectionString = r.Get<Product>().Query().SingleOrDefault(a => a.Name.ToLower() == _productName.ToLower()).ConnectionString;
            }
            using (var r = DBHelper.GetRepository(connectionString))
            {
                return r.Get<Product>().Query().Select(a => new CreateHomeModel { Name = a.Name}).ToList();
            }
        }
        public void IndexPost(CreateHomeModel model)
        {
            using (var r = DBHelper.GetRepository(_productName))
            {
                if(!r.Get<Product>().Query().Any(p => p.Name.ToLower() == model.Name.ToLower()))
                {
                    if(DatabaseHelper.CreateDataBase(model.Name))
                    {
                        r.Get<Product>().Create(new Product() { Name = model.Name });
                    }
                }
            }
        }
    }
}